package com.crb.crm.manage.web.biz.log;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.crb.crm.manage.entity.biz.RestLogSearchDTO;
import com.crb.crm.manage.excel.model.RestLogModel;
import com.crb.crm.manage.excel.model.UserDeviceModel;
import com.crb.crm.manage.pojo.User;
import com.crb.crm.manage.service.biz.RestLogService;
import com.crb.crm.manage.utils.PageDataResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huangjian
 */
@Controller
@RequestMapping("/restLog")
public class RestLogController {
	
	private static final Logger logger = LoggerFactory.getLogger(RestLogController.class);
	@Autowired
	private RestLogService service;
	@RequestMapping("/restLogList")
	public String restLogList() {
		return "biz/log/restLogList";
	}
	
	/**
	 * 分页查询商户列表
	 * @return ok/fail
	 */
	@RequestMapping(value = "/getRestLogs", method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions(value="getRestLogs")
	public PageDataResult getRestLogs(@RequestParam("page") Integer page,
                                   @RequestParam("limit") Integer limit, RestLogSearchDTO searchDTO) {
		logger.debug("分页查询列表！搜索条件：searchDTO：" + searchDTO + ",page:" + page+ ",每页记录数量limit:" + limit);
		PageDataResult pdr = new PageDataResult();
		try {
			if (null == page) {
				page = 1;
			}
			if (null == limit) {
				limit = 10;
			}
			// 获取商户
			pdr = service.getRestLogs(searchDTO, page, limit);
			logger.debug("列表查询=pdr:" + pdr);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("列表查询异常！", e);
		}
		return pdr;
	}

	/**
	 * 删除
	 * @return ok/fail
	 */
	@RequestMapping(value = "/delRestLog", method = RequestMethod.POST)
	@ResponseBody
	@RequiresPermissions("delRestLog")
	public String delRestLog(@RequestParam("id") Integer id) {
		logger.debug("删除restLog！id:" + id);
		String msg = "";
		try {
			if (null == id) {
				logger.debug("删除restLog，结果=请求参数有误，请您稍后再试");
				return "请求参数有误，请您稍后再试";
			}
			User existUser = (User) SecurityUtils.getSubject().getPrincipal();
			if (null == existUser) {
				logger.debug("删除restLog，结果=您未登录或登录超时，请您登录后再试");
				return "您未登录或登录超时，请您登录后再试";
			}
			// 删除商户
			msg = service.delRestLog(id);
			logger.info("删除restLog:" + msg + "。userId=" + id + "，操作用户id:"+ existUser.getId());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("删除restLog异常！", e);
			msg = "操作异常，请您稍后再试";
		}
		return msg;
	}


	/**
	 * 查看日志内容
	 * @return ok/fail
	 */
	@RequestMapping(value = "/showLogs", method = RequestMethod.GET)
	@ResponseBody
	@RequiresPermissions({"showReqData","showContent"})
	public Map<String, Object> showLogs(@RequestParam("logType") String logType, @RequestParam("id") Integer id) {
		logger.debug("查看日志内容！id=" + id+",logType="+logType);
		Map<String, Object> map = new HashMap<>();
		try {
			if (null == id) {
				logger.debug("查看日志内容==请求参数有误，请您稍后再试");
				map.put("msg", "请求参数有误，请您稍后再试");
				return map;
			}
			// 查询商户
			String logContent = service.getRestLogWithBLOBs(id,logType);
			logger.debug("查看日志内容！logContent=" + logContent);
			if (StringUtils.isNotBlank(logContent)) {
				map.put("logContent", logContent);
				map.put("msg", "ok");
			} else {
				map.put("msg", "查看日志内容有误，请您稍后再试");
			}
			logger.debug("查看日志内容数据成功！map=" + map);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "查看日志内容错误，请您稍后再试");
			logger.error("查看日志内容数据异常！", e);
		}
		return map;
	}

	/**
	 * 导出数据
	 * @return ok/fail
	 */
	@RequestMapping(value = "/exportRestLog", method = RequestMethod.GET)
	@RequiresPermissions({"exportRestLog"})
	public void exportRestLog(HttpServletResponse response,RestLogSearchDTO searchDTO) throws IOException {
		logger.debug("导出！searchDTO=" + searchDTO);
		ExcelWriter writer = null;
		OutputStream outputStream = response.getOutputStream();
		try {
			//添加响应头信息
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("REST接口日志"+System.currentTimeMillis()+".xls","UTF-8"));
			response.setHeader("Cache-Control", "No-cache");
			response.flushBuffer();
			//实例化 ExcelWriter
			writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
			//实例化表单
			Sheet sheet = new Sheet(1, 0, RestLogModel.class);
			sheet.setSheetName("日志数据");

			//获取数据
			List<RestLogModel> restLogModels = service.exportRestLog(searchDTO);
			logger.debug("导出！restLogModels=" + restLogModels.size());
			//输出
			writer.write(restLogModels, sheet);
			writer.finish();
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 导出用户设备版本
	 * @return ok/fail
	 */
	@RequestMapping(value = "/exportUserDevice", method = RequestMethod.GET)
	@RequiresPermissions({"exportUserDevice"})
	public void exportUserDevice(HttpServletResponse response,RestLogSearchDTO searchDTO) throws IOException {
		logger.debug("导出！searchDTO=" + searchDTO);
		ExcelWriter writer = null;
		OutputStream outputStream = response.getOutputStream();
		try {
			//添加响应头信息
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("REST接口日志-用户设备版本"+System.currentTimeMillis()+".xls","UTF-8"));
			response.setHeader("Cache-Control", "No-cache");
			response.flushBuffer();
			//实例化 ExcelWriter
			writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
			//实例化表单
			Sheet sheet = new Sheet(1, 0, UserDeviceModel.class);
			sheet.setSheetName("用户设备版本");

			//获取数据
			List<UserDeviceModel> userDeviceModels = service.exportUserDevice(searchDTO);
			logger.debug("导出！userDeviceModels=" + userDeviceModels.size());
			//输出
			writer.write(userDeviceModels, sheet);
			writer.finish();
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
